﻿using BZhanHengjicvWPF.Common;
using BZhanHengjicvWPF.Common.Models;
using BZhanHengjicvWPF.Extensions;
using BZhanHengjicvWPF.Services;
using Microsoft.EntityFrameworkCore.Diagnostics;
using MyToDo.Dtos;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BZhanHengjicvWPF.ViewModels
{
    public class ToDoViewModel : NavigationViewModel
    {
        private readonly IToDoService toDoService;
        private readonly IDialogHostService dialogHost;
        public ToDoViewModel(IToDoService toDoService, IContainerProvider provider, IDialogHostService dialogHost) : base(provider)
        {
            AddCommand = new DelegateCommand(Add);
            this.toDoService = toDoService;
            this.dialogHost = dialogHost;
            //CreatToDoList();
        }
        private ToDoDto currentDto;

        public ToDoDto CurrentDto
        {
            get { return currentDto; }
            set { currentDto = value; RaisePropertyChanged(); }
        }
        private string search;
        /// <summary>
        /// 搜索条件
        /// </summary>
        public string Search
        {
            get { return search; }
            set { search = value; RaisePropertyChanged(); }
        }

        private bool isRightDrawerOpen;
        /// <summary>
        /// 右侧编辑窗口是否展开
        /// </summary>
        public bool IsRightDrawerOpen
        {
            get { return isRightDrawerOpen; }
            set { isRightDrawerOpen = value; RaisePropertyChanged(); }
        }


        public ObservableCollection<ToDoDto> ToDoDtos
        {
            get { return toDoDtos; }
            set { toDoDtos = value; RaisePropertyChanged(); }
        }

        private int selectedIndex;

        public int SelectedIndex
        {
            get { return selectedIndex; }
            set { selectedIndex = value; RaisePropertyChanged(); }
        }
        private ObservableCollection<ToDoDto> toDoDtos = new ObservableCollection<ToDoDto>();


        public DelegateCommand<ToDoDto> SelectedCommand { get { return new DelegateCommand<ToDoDto>(Selected); } }
        public DelegateCommand<string> ExecuteCommand { get { return new DelegateCommand<string>(Execute); } }
        public DelegateCommand AddCommand { get; set; }
        public DelegateCommand<ToDoDto> DeletedCommand { get { return new DelegateCommand<ToDoDto>(Deleted); } }

        private async void Deleted(ToDoDto dto)
        {
            try
            {
                var dialogResult = await dialogHost.Question("温馨提示", $"确认删除代办事项：{dto.Title}?");
                if (dialogResult.Result != Prism.Services.Dialogs.ButtonResult.OK) { return; }

                UpdateLoading(true);
                var deletedResult = await toDoService.DeleteAsync(dto.Id);
                if (deletedResult.Status)
                {
                    var model = ToDoDtos.FirstOrDefault(i => i.Id.Equals(dto.Id));
                    if (model != null)
                    {
                        ToDoDtos.Remove(dto);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally { UpdateLoading(false); }
        }

        private void Execute(string obj)
        {
            switch (obj)
            {
                case "新增": Add(); break;
                case "查询": GetDataSaync(); break;
                case "保存": Save(); break;
                default:
                    break;
            }
        }

        private async void Save()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(CurrentDto.Title) ||
                     string.IsNullOrWhiteSpace(CurrentDto.Content)) return;
                UpdateLoading(true);
                if (CurrentDto.Id > 0)
                {
                    var updateResult = await toDoService.UpdateAsync(CurrentDto);
                    if (updateResult.Status)
                    {
                        var todo = toDoDtos.FirstOrDefault(i => i.Id == CurrentDto.Id);
                        todo.Title = CurrentDto.Title;
                        todo.Content = CurrentDto.Content;
                        todo.Status = CurrentDto.Status;
                        IsRightDrawerOpen = false;
                        GetDataSaync();
                    }
                }
                else
                {
                    var addResult = await toDoService.AddAsync(CurrentDto);
                    if (addResult.Status)
                    {
                        toDoDtos.Add(addResult.Result);
                        IsRightDrawerOpen = false;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally { UpdateLoading(false); }
        }



        private async void Selected(ToDoDto obj)
        {
            try
            {
                IsRightDrawerOpen = true;
                var todoResult = await toDoService.GetFirstOfDefaultAsync(obj.Id);
                if (todoResult.Status)
                {
                    CurrentDto = todoResult.Result;
                    IsRightDrawerOpen = true;
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                UpdateLoading(false);
            }
        }



        async void GetDataSaync()
        {
            UpdateLoading(true);
            int? status = SelectedIndex == 0 ? null : SelectedIndex == 2 ? 1 : 0;
            var toDoResult = await toDoService.GetAllFilterAsync(new MyToDo.Shared.Parameters.ToDoParameter()
            { //读取数据
                PageIndex = 0,
                PageSize = 100,
                Search = Search,
                Status = status,
            });
            if (toDoResult.Status)
            {
                toDoDtos.Clear();
                foreach (var item in toDoResult.Result.Items)
                {
                    toDoDtos.Add(item);
                }
            }
            UpdateLoading(false);
        }

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            if (navigationContext.Parameters.ContainsKey("Value"))
            {
                selectedIndex = navigationContext.Parameters.GetValue<int>("Value");
            }
            else
                selectedIndex = 0;
            GetDataSaync();
        }


        private void Add()
        {
            CurrentDto = new ToDoDto();
            IsRightDrawerOpen = true;
        }
    }
}
